package com.iwhalecloud.bss.kite.cucc.service.custview.userinfo;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Component;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.custview.userinfo.supplier.AbstractUserAttrSupplier;

import com.ztesoft.bss.common.util.SpringUtil;

/**
 * @ClassName : UserAttrSupplierFactory
 * @Description : 用户属性提供者工厂
 * @Author : xie.zhengjun
 * @Date : 2021/3/13 19:50
 */
@Component
public class UserAttrSupplierFactory {
    private static final Map<String, Class<? extends AbstractUserAttrSupplier>> USER_ATTR_SUPPLIERS = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        Map<String, ? extends AbstractUserAttrSupplier> userAttrSupplierMap = SpringUtil.getApplicationContext()
            .getBeansOfType(AbstractUserAttrSupplier.class);
        if (KiteMapUtils.isNotEmpty(userAttrSupplierMap)) {
            userAttrSupplierMap.forEach((s, o) -> {
                Class<? extends AbstractUserAttrSupplier> clazz = o.getClass();
                UserAttrSupplier userAttrSupplier = clazz.getDeclaredAnnotation(UserAttrSupplier.class);
                if (Objects.nonNull(userAttrSupplier) && KiteStringUtils.isNotEmpty(userAttrSupplier.attrField())) {
                    USER_ATTR_SUPPLIERS.put(userAttrSupplier.attrField(), clazz);
                }
            });
        }
    }

    public AbstractUserAttrSupplier getUserAttrSupplier(@NotNull UserInfoContext userInfoContext)
        throws IllegalAccessException, InstantiationException {
        String attrField = userInfoContext.getAttrCode();
        if (KiteStringUtils.isEmpty(attrField)) {
            return null;
        }
        Class<? extends AbstractUserAttrSupplier> clazz = USER_ATTR_SUPPLIERS.get(attrField);
        if (Objects.isNull(clazz)) {
            return null;
        }
        AbstractUserAttrSupplier userAttrSupplier = clazz.newInstance();
        userAttrSupplier.setUserInfoContext(userInfoContext);
        return userAttrSupplier;
    }
}
